<template>
  <div class="chat-container">
    <!-- 顶部工具栏 -->
    <ChatToolbar @back="toHome" @send="sendUserMessage" @file-select="handleFileSelect" />
    
    <!-- 消息列表 -->
    <div class="message-wrapper" ref="messageContainerRef">
      <MessageList :message-list="messageList" @button-click="handleButtonClick" />
    </div>
    
    <!-- 日期选择组件 -->
    <DatetimePicker
      ref="datetimePicker"
      :min-date="new Date(new Date().getTime() + 24 * 60 * 60 * 1000)"
      :max-date="new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000)"
      @confirm="handleDateConfirm"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { ChatToolbar, MessageList, DatetimePicker } from './components';
import { useChatLogic } from './hooks/useChatLogic';

export default defineComponent({
  name: 'ChatView',
  components: {
    ChatToolbar,
    MessageList,
    DatetimePicker,
  },
  
  setup() {
    // 引入聊天逻辑Hook
    const {
      messageList,
      inputText,
      sendMessage,
      handleImageUpload,
      generateAIReply,
      toHome
    } = useChatLogic();
    
    // 消息容器引用
    const messageContainerRef = ref<HTMLElement | null>(null);
    
    // 引用日期选择器
    const datetimePicker = ref();
    
    // 发送用户消息
    const sendUserMessage = (message: string) => {
      if (!message.trim()) return;
      
      sendMessage(message);
      
      // 确保消息发送后滚动到底部
      setTimeout(() => {
        scrollToBottom();
      }, 100);
    };
    
    // 处理文件选择
    const handleFileSelect = (event: Event) => {
      const target = event.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        const file = target.files[0];
        const reader = new FileReader();
        
        reader.onload = (e) => {
          if (e.target && typeof e.target.result === 'string') {
            handleImageUpload(e.target.result);
            
            // 确保图片上传后滚动到底部
            setTimeout(() => {
              scrollToBottom();
            }, 100);
          }
        };
        
        reader.readAsDataURL(file);
      }
    };
    
    // 处理图片上传（保留原方法兼容性）
    const uploadImage = (file: any) => {
      if (file && file.content) {
        handleImageUpload(file.content);
        
        // 确保图片上传后滚动到底部
        setTimeout(() => {
          scrollToBottom();
        }, 100);
      }
    };
    
    // 处理按钮点击事件
    const handleButtonClick = (message: string) => {
      generateAIReply(message);
      
      // 确保消息发送后滚动到底部
      setTimeout(() => {
        scrollToBottom();
      }, 100);
    };
    
    // 处理日期确认
    const handleDateConfirm = (date: Date) => {
      const formatDate = date.toLocaleDateString();
      messageList.value.push({ id: 2, type: 'info', cont: formatDate });
      
      // 确保日期选择后滚动到底部
      setTimeout(() => {
        scrollToBottom();
      }, 100);
      
      // 处理2025年的特定逻辑
      if (date.getFullYear() === 2025) {
        sendMessage('2025');
      }
    };
    
    // 滚动到底部的函数
    const scrollToBottom = () => {
      if (messageContainerRef.value) {
        messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
      }
    };
    
    // 监听按钮事件
    onMounted(() => {
      // 监听全局的预约时间选择事件
      window.addEventListener('showDatetimePicker', () => {
        datetimePicker.value?.show();
      });
      
      // 对消息列表容器进行初始滚动
      setTimeout(() => {
        scrollToBottom();
      }, 300);
    });
    
    return {
      messageList,
      inputText,
      messageContainerRef,
      datetimePicker,
      sendUserMessage,
      uploadImage,
      handleFileSelect,
      handleDateConfirm,
      handleButtonClick,
      toHome,
      scrollToBottom
    };
  }
});
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7;
  
  .message-wrapper {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
    margin-bottom: 60px; /* 为底部工具栏留出空间 */
    -webkit-overflow-scrolling: touch; /* 增强iOS滚动体验 */
  }
}
</style>
